﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
    ViewData["Title"] = "添加物料入库单";
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>添加物料入库单</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" media="all">
    <style>
        body {
            background-color: #f5f7fa;
            font-family: 'Microsoft YaHei', 'PingFang SC', Arial, sans-serif;
            margin: 0;
            padding: 20px 0;
        }
        .form-container {
            max-width: 1200px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }
        .form-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px 40px;
            text-align: center;
        }
        .form-title {
            font-size: 20px;
            font-weight: 500;
            margin: 0;
        }
        .form-body {
            padding: 40px;
        }
        .layui-form-item {
            margin-bottom: 28px;
        }
        .form-row {
            display: flex;
            gap: 30px;
            margin-bottom: 28px;
        }
        .form-col {
            flex: 1;
        }
        .layui-form-label {
            width: 140px;
            padding: 0;
            color: #2d3748;
            font-weight: 500;
            background: none;
            border: none;
            text-align: right;
            line-height: 44px;
            float: left;
        }
        .layui-input-block {
            margin-left: 160px;
        }
        .layui-input, .layui-select, .layui-textarea {
            height: 44px;
            line-height: 44px;
            padding: 0 15px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.2s ease;
            background: #fff;
        }
        .layui-select[disabled] {
            background: #f7fafc;
            color: #a0aec0;
            cursor: not-allowed;
            border-color: #e2e8f0;
        }
        .layui-input:focus, .layui-select:focus, .layui-textarea:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            outline: none;
        }
        .layui-textarea {
            height: auto;
            line-height: 1.5;
            padding: 12px 15px;
            min-height: 80px;
            resize: vertical;
        }
        .auto-generate-wrapper {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .auto-generate-wrapper .layui-input {
            flex: 1;
            min-width: 300px;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 13px;
        }
        .switch-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 15px;
            background: #f7fafc;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            font-size: 12px;
            color: #4a5568;
            cursor: pointer;
            transition: all 0.2s ease;
            white-space: nowrap;
            flex-shrink: 0;
        }
        .switch-btn:hover {
            background: #edf2f7;
            border-color: #cbd5e0;
        }
        .supplier-wrapper {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .supplier-wrapper .layui-input {
            flex: 1;
        }
        .supplier-select-btn {
            width: 44px;
            height: 44px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            background: #fff;
            color: #667eea;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            flex-shrink: 0;
        }
        .supplier-select-btn:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        .required-mark {
            color: #e53e3e;
            margin-right: 4px;
        }
        .form-actions {
            padding: 30px 40px;
            background: #f7fafc;
            text-align: center;
            border-top: 1px solid #e2e8f0;
        }
        .layui-btn {
            height: 44px;
            line-height: 44px;
            padding: 0 32px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin-right: 12px;
        }
        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        .btn-default {
            background: #fff;
            color: #4a5568;
            border: 1px solid #e2e8f0;
        }
        .btn-default:hover {
            background: #f7fafc;
            border-color: #cbd5e0;
        }
        .layui-input.disabled {
            background: #f7fafc;
            color: #a0aec0;
            cursor: not-allowed;
        }
        .layui-input[readonly] {
            background: #f7fafc;
            color: #a0aec0;
            cursor: not-allowed;
        }
        .layui-form-item::after {
            content: "";
            display: block;
            clear: both;
        }
        
        /* 响应式设计 */
        @@media (max-width: 768px) {
            body {
                padding: 10px;
            }
            .form-header, .form-body, .form-actions {
                padding: 20px;
            }
            .form-row {
                flex-direction: column;
                gap: 0;
            }
            .layui-input-block {
                margin-left: 0;
            }
            .layui-form-label {
                width: auto;
                text-align: left;
                float: none;
                line-height: normal;
                margin-bottom: 8px;
            }
            .auto-generate-wrapper {
                flex-direction: column;
                align-items: stretch;
            }
            .switch-btn {
                align-self: flex-start;
                margin-top: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="form-container">
        <div class="form-header">
            <h1 class="form-title">添加物料入库单</h1>
        </div>
        <div class="form-body">
            <form class="layui-form" lay-filter="procurementForm">
                @Html.AntiForgeryToken()
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>入库单编号</label>
                            <div class="layui-input-block">
                                <div class="auto-generate-wrapper">
                                    <input type="text" name="LnboundCode" placeholder="请输入入库单编号" autocomplete="off" class="layui-input" id="lnboundCodeInput">
                                    <div class="switch-btn">
                                        <input type="checkbox" name="AutoGenerate" title="自动生成" lay-skin="switch" lay-filter="autoGenerateCode">
                                        <span>自动生成</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>入库单名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="LnboundName" placeholder="请输入入库单名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>入库日期</label>
                            <div class="layui-input-block">
                                <input type="text" name="LnboundDate" id="lnboundDate" placeholder="请选择入库日期" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>采购订单号</label>
                            <div class="layui-input-block">
                                <input type="text" name="ProcurementNumber" id="procurementNumber" placeholder="请输入采购订单号" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>供应商</label>
                            <div class="layui-input-block">
                                <div class="supplier-wrapper">
                                    <input type="text" name="Vendor" placeholder="请选择供应商" autocomplete="off" class="layui-input" readonly>
                                    <input type="hidden" name="SupplierId" id="supplierId">
                                    <button type="button" class="supplier-select-btn" id="selectSupplierBtn">
                                        <i class="layui-icon layui-icon-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>入库仓库</label>
                            <div class="layui-input-block">
                                <select name="LnboundWarehouse" lay-search="">
                                    <option value="">请选择入库仓库</option>
                                    <option value="原料仓库">原料仓库</option>
                                    <option value="成品仓库">成品仓库</option>
                                    <option value="半成品仓库">半成品仓库</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>单据状态</label>
                            <div class="layui-input-block">
                                <select name="DocumentStatus" disabled>
                                    <option value="0" selected>草稿</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span class="required-mark">*</span>总金额</label>
                            <div class="layui-input-block">
                                <input type="text" name="TotalAmount" placeholder="请输入总金额" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label"><span class="required-mark">*</span>备注</label>
                    <div class="layui-input-block">
                        <textarea name="Pemark" placeholder="请输入备注内容" class="layui-textarea"></textarea>
                    </div>
                </div>
            </form>
        </div>
        <div class="form-actions">
            <button class="layui-btn btn-primary" lay-submit lay-filter="procurementSubmit">
                <i class="layui-icon layui-icon-ok"></i> 确定提交
            </button>
            <button type="button" class="layui-btn btn-default" id="cancelBtn">
                <i class="layui-icon layui-icon-return"></i> 取消返回
            </button>
        </div>
    </div>

    <script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
    layui.use(['form', 'layer', 'laydate', 'table'], function () {
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var table = layui.table;
        var $ = layui.$;

        // 初始化日期选择器
        laydate.render({
            elem: '#lnboundDate',
            type: 'date',
            value: new Date()
        });

        // 雪花ID生成函数
        function generateSnowflakeId() {
            // 简单雪花算法实现（仅前端，实际可用后端生成）
            var timestamp = Date.now();
            var random = Math.floor(Math.random() * 1000);
            return timestamp.toString() + random.toString().padStart(3, '0');
        }

        // 页面加载时初始化
        $(document).ready(function() {
            // 自动生成开关初始化
            var $codeInput = $('#lnboundCodeInput');
            var $autoSwitch = $('input[name="AutoGenerate"]');
            
            // 默认为手动输入模式
            $autoSwitch.prop('checked', false);
            $codeInput.val('').prop('readonly', false);
            form.render('checkbox');
        });

        // 自动生成开关事件
        form.on('switch(autoGenerateCode)', function(data){
            var $input = $('#lnboundCodeInput');
            
            if(data.elem.checked){
                // 生成雪花ID
                var snowflakeId = generateSnowflakeId();
                $input.val(snowflakeId);
                $input.prop('readonly', true);
                $input.addClass('disabled');
                
                // 显示生成成功提示
                layer.msg('已自动生成编号: ' + snowflakeId, {
                    icon: 1,
                    time: 2000
                });
            } else {
                $input.val('');
                $input.prop('readonly', false);
                $input.removeClass('disabled');
            }
        });

        // 前端表单验证函数
        function validateForm(formData) {
            // 入库单编号验证 - 从输入框直接获取值
            var lnboundCode = $('#lnboundCodeInput').val();
            if (!lnboundCode || lnboundCode.trim() === '') {
                layer.msg('请输入入库单编号', {icon: 2});
                return false;
            }
            // 确保formData中有正确的值
            formData.LnboundCode = lnboundCode;
            
            // 入库单名称验证
            if (!formData.LnboundName || formData.LnboundName.trim() === '') {
                layer.msg('请输入入库单名称', {icon: 2});
                return false;
            }
            
            // 入库日期验证
            if (!formData.LnboundDate || formData.LnboundDate.trim() === '') {
                layer.msg('请选择入库日期', {icon: 2});
                return false;
            }
            
            // 采购订单号验证
            if (!formData.ProcurementNumber || formData.ProcurementNumber.trim() === '') {
                layer.msg('请输入采购订单号', {icon: 2});
                return false;
            }
            
            // 供应商验证
            if (!formData.Vendor || formData.Vendor.trim() === '') {
                layer.msg('请选择供应商', {icon: 2});
                return false;
            }
            
            // 入库仓库验证
            if (!formData.LnboundWarehouse || formData.LnboundWarehouse.trim() === '') {
                layer.msg('请选择入库仓库', {icon: 2});
                return false;
            }
            
            // 单据状态验证（固定为草稿状态）
            if (formData.DocumentStatus === undefined || formData.DocumentStatus === null || formData.DocumentStatus === '') {
                formData.DocumentStatus = '0'; // 默认设置为草稿状态
            }
            
            // 总金额验证（必填且必须是有效数字）
            if (!formData.TotalAmount || formData.TotalAmount.trim() === '') {
                layer.msg('请输入总金额', {icon: 2});
                return false;
            }
            var amount = parseFloat(formData.TotalAmount);
            if (isNaN(amount) || amount < 0) {
                layer.msg('请输入有效的总金额', {icon: 2});
                return false;
            }
            
            // 备注验证（必填）
            if (!formData.Pemark || formData.Pemark.trim() === '') {
                layer.msg('请输入备注内容', {icon: 2});
                return false;
            }
            
            return true;
        }

        // 表单提交
        form.on('submit(procurementSubmit)', function(data){
            // 手动收集所有字段的值，确保包含只读字段和禁用字段
            var formData = {
                LnboundCode: $('#lnboundCodeInput').val(),
                LnboundName: $('input[name="LnboundName"]').val(),
                LnboundDate: $('input[name="LnboundDate"]').val(),
                ProcurementNumber: $('input[name="ProcurementNumber"]').val(),
                Vendor: $('input[name="Vendor"]').val(),
                LnboundWarehouse: $('select[name="LnboundWarehouse"]').val(),
                DocumentStatus: $('select[name="DocumentStatus"] option:selected').val() || '0', // 确保获取到禁用select的值
                TotalAmount: $('input[name="TotalAmount"]').val(),
                Pemark: $('textarea[name="Pemark"]').val(),
                SupplierId: $('#supplierId').val()
            };
            
            // 调试信息
            console.log('=== 表单数据收集 ===');
            console.log('入库单编号:', formData.LnboundCode);
            console.log('入库单名称:', formData.LnboundName);
            console.log('入库日期:', formData.LnboundDate);
            console.log('采购订单号:', formData.ProcurementNumber);
            console.log('供应商:', formData.Vendor);
            console.log('入库仓库:', formData.LnboundWarehouse);
            console.log('单据状态:', formData.DocumentStatus);
            console.log('总金额:', formData.TotalAmount);
            console.log('备注:', formData.Pemark);
            console.log('完整表单数据:', formData);
            
            // 前端验证
            if (!validateForm(formData)) {
                return false;
            }
            
            var loading = layer.load(2, {
                content: '正在提交...',
                time: 10*1000
            });
            
            // 转换日期格式
            if (formData.LnboundDate) {
                formData.LnboundDate = new Date(formData.LnboundDate).toISOString();
            }
            
            // 转换数字类型
            formData.DocumentStatus = parseInt(formData.DocumentStatus);
            
            // 发送新增请求
            $.ajax({
                url: '/WarehouseManagement/CreateProcurement',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(result) {
                    layer.close(loading);
                    if (result.success) {
                        layer.msg('保存成功', {
                            icon: 1,
                            time: 2000
                        }, function() {
                            window.location.href = '/WarehouseManagement/ProcurementView';
                        });
                    } else {
                        layer.msg('保存失败：' + result.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.close(loading);
                    layer.msg('保存失败', {icon: 2});
                }
            });
            
            return false; // 阻止表单跳转
        });

        // 供应商选择按钮
        $('#selectSupplierBtn').on('click', function() {
            openSupplierSelectDialog();
        });

        // 打开供应商选择对话框
        function openSupplierSelectDialog() {
            var supplierDialog = layer.open({
                type: 1,
                title: '供应商选择',
                area: ['1000px', '600px'],
                maxmin: true,
                content: `
                    <div style="padding: 20px;">
                        <!-- 搜索表单 -->
                        <form class="layui-form" lay-filter="supplierSearchForm" style="margin-bottom: 20px;">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">供应商编码</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="supplierCode" placeholder="请输入供应商编码" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">供应商名称</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="supplierName" placeholder="请输入供应商名称" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button type="button" class="layui-btn" id="supplierSearchBtn">
                                        <i class="layui-icon layui-icon-search"></i> 搜索
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-primary" id="supplierResetBtn">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </form>
                        
                        <!-- 供应商列表表格 -->
                        <table class="layui-hide" id="supplierTable" lay-filter="supplierTable"></table>
                        
                        <!-- 操作按钮 -->
                        <div style="text-align: center; margin-top: 20px;">
                            <button type="button" class="layui-btn" id="confirmSelectBtn">确定</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="cancelSelectBtn">取消</button>
                        </div>
                    </div>
                `,
                success: function(layero, index) {
                    // 初始化供应商表格
                    initSupplierTable();
                    
                    // 绑定搜索按钮事件
                    $('#supplierSearchBtn').on('click', function() {
                        loadSupplierData();
                    });
                    
                    // 绑定重置按钮事件
                    $('#supplierResetBtn').on('click', function() {
                        $('input[name="supplierCode"]').val('');
                        $('input[name="supplierName"]').val('');
                        loadSupplierData();
                    });
                    
                    // 绑定确定按钮事件
                    $('#confirmSelectBtn').on('click', function() {
                        var checkStatus = layui.table.checkStatus('supplierTable');
                        if (checkStatus.data.length === 0) {
                            layer.msg('请选择一个供应商', {icon: 2});
                            return;
                        }
                        if (checkStatus.data.length > 1) {
                            layer.msg('只能选择一个供应商', {icon: 2});
                            return;
                        }
                        
                        var selectedSupplier = checkStatus.data[0];
                        $('input[name="Vendor"]').val(selectedSupplier.supplierName);
                        $('#supplierId').val(selectedSupplier.id);
                        
                        layer.close(index);
                        layer.msg('供应商选择成功', {icon: 1});
                    });
                    
                    // 绑定取消按钮事件
                    $('#cancelSelectBtn').on('click', function() {
                        layer.close(index);
                    });
                }
            });
        }

        // 初始化供应商表格
        function initSupplierTable() {
            layui.table.render({
                elem: '#supplierTable',
                url: '/ProductionSystem/SupplierModel/GetSupplierList',
                method: 'GET',
                page: true,
                limit: 10,
                limits: [10, 20, 50],
                cols: [[
                    {type: 'radio', fixed: 'left'},
                    {field: 'supplierCode', title: '供应商编码', width: 120},
                    {field: 'supplierName', title: '供应商名称', width: 150},
                    {field: 'supplierGrade', title: '供应商等级', width: 120},
                    {field: 'supplierPhone', title: '供应商电话', width: 130},
                    {field: 'isEnable', title: '是否启用', width: 100, templet: function(d) {
                        return d.isEnable ? '<span style="color: #1890ff;">是</span>' : '<span style="color: #999;">否</span>';
                    }}
                ]],
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                where: {
                    supplierCode: '',
                    supplierName: ''
                }
            });
        }

        // 加载供应商数据
        function loadSupplierData() {
            var supplierCode = $('input[name="supplierCode"]').val();
            var supplierName = $('input[name="supplierName"]').val();
            
            layui.table.reload('supplierTable', {
                where: {
                    supplierCode: supplierCode,
                    supplierName: supplierName
                },
                page: {
                    curr: 1
                }
            });
        }

        // 取消按钮
        $('#cancelBtn').on('click', function() {
            layer.confirm('确认要取消吗？未保存的数据将丢失', {
                icon: 3,
                title: '确认操作'
            }, function(index) {
                window.location.href = '/WarehouseManagement/ProcurementView';
                layer.close(index);
            });
        });
    });
    </script>
</body>
</html>


